package org.jeecg.modules.basic.material.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.basic.material.entity.BasicMaterial;
import org.jeecg.modules.basic.material.entity.WmsBasicMaterialStockInfo;
import org.jeecg.modules.basic.material.mapper.BasicMaterialMapper;
import org.jeecg.modules.basic.material.mapper.WmsBasicMaterialStockInfoMapper;
import org.jeecg.modules.basic.material.service.IBasicMaterialService;
import org.jeecg.modules.basic.materialtype.entity.BasicMaterialType;
import org.jeecg.modules.basic.materialtype.service.IBasicMaterialTypeService;
import org.jeecg.modules.basic.unit.entity.BasicUnit;
import org.jeecg.modules.basic.unit.service.IBasicUnitService;
import org.jeecg.modules.business.repertory.entity.WmsRepertory;
import org.jeecg.modules.business.repertory.mapper.WmsRepertoryMapper;
import org.jeecg.modules.business.transfer.entity.PaperWarning;
import org.jeecg.modules.business.transfer.entity.WmsMoveReceiptMaterial;
import org.jeecg.modules.business.transfer.mapper.PaperWarningMapper;
import org.jeecg.modules.business.transfer.service.IWmsMoveReceiptMaterialService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.List;
import java.util.Map;

/**
 * @Description: 物料信息管理
 * @Author: jeecg-boot
 * @Date: 2023-07-27
 * @Version: V1.0
 */
@Slf4j
@Service
public class BasicMaterialServiceImpl extends ServiceImpl<BasicMaterialMapper, BasicMaterial> implements IBasicMaterialService {

    @Autowired
    private BasicMaterialMapper basicMaterialMapper;

    @Autowired
    private IBasicMaterialTypeService basicMaterialTypeService;

    @Value("${transtella.bus.factory}")
    private String factory;

    @Autowired
    private IBasicUnitService iBasicUnitService;

    @Autowired
    private IWmsMoveReceiptMaterialService moveReceiptMaterialService;

    @Autowired
    private WmsBasicMaterialStockInfoMapper materialStockInfoMapper;

    @Autowired
    private WmsRepertoryMapper wmsRepertoryMapper;

    @Autowired
    private PaperWarningMapper paperWarningMapper;

    public static void main(String[] args) {
        String code = "112aa112aa112aaaaa";
        String s = addZero(code);
        System.out.println(s + ":" + s.length());
    }

    public static String addZero(String code) {
        final int num = 18;
        if (StringUtils.isBlank(code)) {
            return "";
        }
        if (code.length() < 18) {
            int addNum = num - code.length();
            StringBuffer stringBuffer = new StringBuffer("");
            for (int i = 0; i < addNum; i++) {
                stringBuffer.append("0");
            }
            return stringBuffer.append(code).toString();
        }
        return code;
    }

    /**
     * 分页查询物料
     *
     * @return
     */
    @Override
    public Page<BasicMaterial> listMaterialByPage(Page<BasicMaterial> page, BasicMaterial basicMaterial) {
        List<String> typeIds = new ArrayList<>();
        if (StringUtils.isNotBlank(basicMaterial.getMaterialTypeId())) {
            typeIds = basicMaterialTypeService.listIdsByPid(basicMaterial.getMaterialTypeId());
        }
        basicMaterial.setMaterialTypeIds(typeIds);
        return page.setRecords(basicMaterialMapper.listMaterialByPage(page, basicMaterial));
    }

    /**
     * 根据物料编码查询物料信息
     *
     * @param code
     * @return
     */
    @Override
    public BasicMaterial getByCode(String code) {
        BasicMaterial material = this.getOne(new LambdaQueryWrapper<BasicMaterial>()
                .eq(BasicMaterial::getCode, code)
                .last("limit 1"));
        return material;
    }

    /**
     * 导入
     *
     * @param request
     * @return
     */
    @Override
    public Result<String> importExcel(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<BasicMaterial> list = ExcelImportUtil.importExcel(file.getInputStream(), BasicMaterial.class, params);
                for (BasicMaterial material : list) {
                    if (org.apache.commons.lang.StringUtils.isBlank(material.getName())) {
                        return Result.error("文件导入失败:物料名称不能为空！");
                    }
                    if (org.apache.commons.lang.StringUtils.isBlank(material.getStatus())) {
                        return Result.error("文件导入失败:状态不能为空！");
                    }
                    if (!"0".equals(material.getStatus()) && !"1".equals(material.getStatus())) {
                        return Result.error("文件导入失败:状态只能填启用或禁用！");
                    }
                    List<BasicMaterial> names = this.list(new LambdaQueryWrapper<BasicMaterial>()
                            .eq(BasicMaterial::getName, material.getName()));
                    if (CollectionUtil.isNotEmpty(names)) {
                        return Result.error("文件导入失败:物料名称 " + material.getName() + " 系统中已存在！");
                    }
                    Object result = FillRuleUtil.executeRule(FillRuleConstant.BASIC_CUSTOMER, new JSONObject());
                    material.setCode(result.toString());
                }
                this.saveBatch(list);
                return Result.OK("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                String msg = e.getMessage();
                log.error(msg, e);
                if (msg != null && msg.indexOf("Duplicate entry") >= 0) {
                    return Result.error("文件导入失败:有重复数据！");
                } else {
                    return Result.error("文件导入失败:" + e.getMessage());
                }
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    @Override
    public void updateUsedState(String materialId) {
//        if (StringUtils.isBlank(materialId)) {
//            return;
//        }
//        Integer count = basicMaterialMapper.selectCountByMaterialId(materialId);
//        BasicMaterial material = basicMaterialMapper.selectById(materialId);
//        if(ObjectUtils.isNotEmpty(material)){
//            material.setId(materialId);
//            if (count > 0) {
//                material.setUsed(1);
//            } else {
//                material.setUsed(0);
//            }
//            basicMaterialMapper.updateById(material);
//        }
    }

    @Override
    public void stockWarning(String moveReceiptId) {
        List<WmsMoveReceiptMaterial> receiptMaterials = moveReceiptMaterialService.list(new LambdaQueryWrapper<WmsMoveReceiptMaterial>()
                .eq(WmsMoveReceiptMaterial::getWmsMoveReceiptId, moveReceiptId));
        for (WmsMoveReceiptMaterial receiptMaterial : receiptMaterials) {
            WmsBasicMaterialStockInfo materialStockInfo = materialStockInfoMapper.selectOne(new LambdaQueryWrapper<WmsBasicMaterialStockInfo>()
                    .eq(WmsBasicMaterialStockInfo::getWmsBasicMaterialId, receiptMaterial.getWmsBasicMaterialId())
                    .eq(WmsBasicMaterialStockInfo::getWarehouseAreaId, receiptMaterial.getTransferFromAreaId()));
            if (materialStockInfo == null){
                log.error("物料id：{}，库区id：{} 未找到对应物料库位信息",receiptMaterial.getWmsBasicMaterialId(),
                        receiptMaterial.getTransferFromAreaId());
                continue;
            }
            //安全库存为空 不预警
            if (materialStockInfo.getSafeInventory() == null
                    || materialStockInfo.getSafeInventory().compareTo(BigDecimal.valueOf(0)) != 1){
                continue;
            }
            WmsRepertory wmsRepertory = wmsRepertoryMapper.selectOne(new LambdaQueryWrapper<WmsRepertory>()
                    .eq(WmsRepertory::getMaterialId, receiptMaterial.getWmsBasicMaterialId())
                    .eq(WmsRepertory::getWmsBasicWarehouseAreaId, receiptMaterial.getTransferFromAreaId()));
            if (wmsRepertory == null){
                log.error("物料id：{}，库区id：{} 未找到对应的即时库存信息",receiptMaterial.getWmsBasicMaterialId(),
                        receiptMaterial.getTransferFromAreaId());
                continue;
            }

            if (wmsRepertory.getStockQuantity().compareTo(materialStockInfo.getSafeInventory()) != 1){
                BasicMaterial material = basicMaterialMapper.selectById(receiptMaterial.getWmsBasicMaterialId());
                PaperWarning paperWarning = new PaperWarning();
                paperWarning.setMaterialId(receiptMaterial.getWmsBasicMaterialId());
                paperWarning.setWarehouseId(wmsRepertory.getWmsBasicWarehouseId());
                paperWarning.setWarehouseAreaId(receiptMaterial.getTransferFromAreaId());
                paperWarning.setStockQuantity(wmsRepertory.getStockQuantity()+"");
                paperWarning.setSafeInventory(materialStockInfo.getSafeInventory().toPlainString());
                paperWarning.setMaxInventory(materialStockInfo.getMaxInventory().toPlainString());
                paperWarning.setSysOrgCode(wmsRepertory.getSysOrgCode());
                paperWarning.setWarningTime(new Date());
                paperWarning.setStatus("1");
                paperWarningMapper.insert(paperWarning);
            }
        }



    }

    @Override
    public List<BasicMaterial> listByCode(String code) {
        List<BasicMaterial> list = this.list(new LambdaQueryWrapper<BasicMaterial>().eq(BasicMaterial::getCode, code));
        return list;
    }
}
